//
//  RNToNative.m
//  NativeAddRN
//
//  Created by 曹阳 on 17/5/4.
//  Copyright © 2017年 9elephas. All rights reserved.
//

#import "RNToNative.h"
#import "ViewController.h"
#import "AppDelegate.h"

#import <RCTBridge.h>
#import <RCTEventDispatcher.h>

@implementation RNToNative
{
    BOOL hasListeners;
}


RCT_EXPORT_MODULE(RNToNative);

RCT_EXPORT_METHOD(RNToNativeVC:(NSString *)msg)
{
    NSLog(@"RN传入原生界面的数据为:%@",msg);
    
    //主要这里必须使用主线程发送,不然有可能失效
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSDictionary *info = @{@"name": @"young"};
        [self backToNativeEventReceived:info];
        
        AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [app.nav popViewControllerAnimated:YES];
    });
}


#pragma 给 RN 发送事件

- (void)startObserving
{
    hasListeners = YES;
}

- (void)stopObserving
{
    hasListeners = NO;
}

//  进行设置发送事件通知给JavaScript端
- (void)backToNativeEventReceived:(NSDictionary *)info
{
    NSString *name = info[@"name"];
    
    if (hasListeners)
    {
        [self sendEventWithName:@"BackToNative" body:@{@"name": name}];
    }
}

- (NSArray<NSString *> *)supportedEvents
{
    return @[@"BackToNative"];
}

@end
